<!--
  module - 用户与权限--- 添加及编辑用户

  @author wuh 2020-05-08
-->
<template>
  <div class="mixin-components-container">
    <el-col :span="24">
      <el-card>

        <div slot="header" class="clearfix">
          <template>
            <el-page-header :content="titleContent" @back="goBack" />
          </template>
        </div>
        <div>
          <div>
            <div style="margin-bottom:50px;">
              <el-form
                ref="form"
                :model="form"
                :rules="rules"
                label-width="140px"
                style="padding: 25px 0;"
                :disabled="$route.query.type === '3' ? true : false"
              >
                <el-row :gutter="20">
                  <el-col :span="7">
                    <el-form-item prop="userName" label="用户名称">
                      <el-input
                        v-model="form.userName"
                        placeholder="请填写用户名称"
                        maxlength="50"
                        show-word-limit
                        clearable
                      />
                    </el-form-item>
                    <el-form-item v-if="$route.query.type === '1'" prop="passWord" label="密码">
                      <el-input v-model="form.passWord" type="password" placeholder="请填写密码" show-password />
                    </el-form-item>
                    <el-form-item v-else label="密码">
                      <el-input v-model="form.passWord" type="password" placeholder="********" show-password />
                    </el-form-item>
                    <el-form-item prop="realName" label="真实姓名">
                      <el-input
                        v-model="form.realName"
                        placeholder="请填写真实姓名"
                        maxlength="50"
                        show-word-limit
                        clearable
                      />
                    </el-form-item>
                    <el-form-item prop="status" label="是否锁定">
                      <el-switch v-model="form.status" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="7">
                    <el-form-item prop="depId" label="部门">
                      <el-cascader v-model="form.depId" :options="options" :props="treeProps" clearable />
                    </el-form-item>
                    <el-form-item prop="phone" label="电话">
                      <el-input
                        v-model="form.phone"
                        placeholder="请填写电话"
                        maxlength="20"
                        show-word-limit
                        clearable
                      />
                    </el-form-item>
                    <el-form-item prop="email" label="邮箱">
                      <el-input
                        v-model="form.email"
                        placeholder="请填写邮箱"
                        maxlength="30"
                        show-word-limit
                        clearable
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="10">
                    <el-form-item prop="head" label="用户头像">
                      <el-upload
                        class="avatar-uploader"
                        action=""
                        list-type="picture-card"
                        :show-file-list="false"
                        :on-success="handleAvatarSuccess"
                        :before-upload="beforeAvatarUpload"
                        :http-request="uploadImage"
                      >
                        <img v-if="form.imgUrl" :src="form.imgUrl" class="avatar">
                        <i v-else class="el-icon-plus avatar-uploader-icon" />
                      </el-upload>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
              <el-row style="padding-left:140px;">
                <!-- <el-button
                  v-if="$route.query.type === '1' || $route.query.type === '2'"
                  waves
                  type="primary"
                  @click="submitForm('form')"
                >
                  保存
                </el-button> -->
                <el-link v-if="$route.query.type === '1' || $route.query.type === '2'" type="primary" size="mini" @click="submitForm('form')">
                  保存
                </el-link>
                <!-- <el-button waves type="info" @click="goBack">取消</el-button> -->
                <el-link type="info" size="mini" @click="goBack">
                  取消
                </el-link>
              </el-row>
            </div>
          </div>
        </div>

      </el-card>
    </el-col>
  </div>
</template>

<script>
// api
import { queryUserInfo, saveUser, updateUser, uploadImageApi } from '@/api/userAndRole/sysUser.js'
import { queryDepartmentList } from '@/api/userAndRole/sysDepartment.js'
// 水波纹插件
import waves from '@/directive/waves'

export default {
  name: 'SysUser',
  directives: { waves },
  data() {
    return {
      listLoading: false,
      titleContent: '',
      treeProps: {
        checkStrictly: true,
        expandTrigger: 'click',
        label: 'name',
        value: 'departmentId'
      },
      options: [],
      form: {
        userId: '',
        depId: '',
        email: '',
        phone: '',
        userName: '',
        passWord: '',
        realName: '',
        head: '',
        imgUrl: '',
        status: false
      },
      rules: {
        depId: [
          { required: true, message: '请选择部门', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请填写邮箱', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请填写电话号码', trigger: 'blur' }
        ],
        userName: [
          { required: true, message: '请填写用户名称', trigger: 'blur' }
        ],
        passWord: [
          { required: true, message: '请填写密码', trigger: 'blur' }
        ],
        realName: [
          { required: true, message: '请填写真实姓名', trigger: 'blur' }
        ],
        head: [
          { required: true, message: '请上传头像', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '请选择是否锁定', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    const curVue = this
    // 设置部门选项
    queryDepartmentList({ multistep: true }).then(res => {
      if (res.code === 1) {
        this.options = res.data.sysDepartmentList
      } else {
        this.noticeUtil.errorMsg('操作失败!')
      }
    })
    if (curVue.$route.query.type === '1') {
      curVue.titleContent = '新建用户'
    } else {
      curVue.form.userId = curVue.$route.query.data
      if (curVue.$route.query.type === '2') {
        curVue.titleContent = '编辑用户'
      } else if (curVue.$route.query.type === '3') {
        curVue.titleContent = '查看用户'
      }
      queryUserInfo({ userId: curVue.form.userId }).then(res => {
        if (res.code === 1) {
          curVue.form.userId = res.data.userId
          curVue.form.depId = res.data.depId
          curVue.form.email = res.data.email
          curVue.form.phone = res.data.phone
          curVue.form.userName = res.data.userName
          curVue.form.realName = res.data.realName
          if (res.data.head.length > 0) {
            curVue.form.head = res.data.head
            curVue.form.imgUrl = res.data.head.startsWith('/images') ? res.data.head : '/fileUp' + res.data.head
          }
          curVue.form.status = res.data.status
        } else {
          this.noticeUtil.errorMsg('操作失败!')
        }
      })
    }
  },
  methods: {
    goBack() {
      this.$router.go(-1)
    },
    handleAvatarSuccess(res, file) {
      this.head = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    uploadImage(param) {
      const formData = new FormData()
      formData.append('multipartFile', param.file)
      uploadImageApi(formData).then(res => {
        console.log(res.data)
        const imgdata = JSON.parse(res.data)
        console.log(imgdata)
        this.form.head = imgdata[0].path
        this.form.imgUrl = '/fileUp' + imgdata[0].path
        console.log(this.form.imgUrl)
      }).catch(response => {
        this.noticeUtil.errorMsg('操作失败!')
      })
    },
    submitForm(formName) {
      const formObj = {
        userId: this.form.userId,
        depId: this.form.depId[this.form.depId.length - 1],
        email: this.form.email,
        phone: this.form.phone,
        userName: this.form.userName,
        passWord: this.form.passWord,
        realName: this.form.realName,
        head: this.form.head,
        status: this.form.status ? 'locked' : 'normal'
      }
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.$route.query.type === '1') {
            saveUser(formObj).then(res => {
              if (res.code === 1) {
                this.noticeUtil.successMsg('操作成功!')
                this.$router.go(-1)
              } else {
                this.noticeUtil.errorMsg('操作失败!')
              }
            })
          } else {
            updateUser(formObj).then(res => {
              if (res.code === 1) {
                this.noticeUtil.successMsg('操作成功!')
                this.$router.go(-1)
              } else {
                this.noticeUtil.errorMsg('操作失败!')
              }
            })
          }
        } else {
          return false
        }
      })
    }
  }
}
</script>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 148px;
    height: 148px;
    line-height: 148px;
    text-align: center;
  }
  .avatar {
    width: 148px;
    height: 148px;
    display: block;
  }
</style>
